package com.code.service.constants;

import java.io.*;

/**
 * @author ggh
 * @date 2023/4/15
 */
public enum SerializableType {
    JDK((byte) 1) {
        @Override
        public <T> byte[] serializable(T t) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(t);

                return baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public <T> T deserizable(byte[] bytes, Class<T> cls) {
            try {
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ObjectInputStream oos = new ObjectInputStream(bais);
                return (T) oos.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    },
    JSON((byte) 2) {
        @Override
        public <T> byte[] serializable(T t) {
            try {
                return com.alibaba.fastjson2.JSON.toJSONBytes(t);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public <T> T deserizable(byte[] bytes, Class<T> cls) {
            try {
                return com.alibaba.fastjson2.JSON.parseObject(bytes, cls);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    };

    private Byte type;

    SerializableType(Byte type) {
        this.type = type;
    }

    public Byte getType() {
        return type;
    }

    public static SerializableType parseType(Byte type) {
        for (SerializableType serializableType : values()) {
            if (serializableType.getType().equals(type)) {
                return serializableType;
            }
        }
        return null;
    }

    public abstract <T> byte[] serializable(T t);

    public abstract <T> T deserizable(byte[] bytes, Class<T> cls);
}
